<template>
	<div class="app-container" v-loading="data.mtloading">
		<el-form :model="data.info" :rules="data.rules" class="w-full" :label-width="language == 'en' ? '170' : '120px'"
			ref="ruleFormRef">

			<el-form-item :label="$t('goods.corner.activitName') + ':'" prop="lottery_name" class="w-1/2">
				<el-input v-model="data.info.lottery_name" :placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<el-form-item :label="$t('marketing.guess.singleLottery') + ':'" prop="price" class="w-1/2">
				<el-input v-model="data.info.price" :placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<el-form-item :label="$t('goods.corner.timeType') + ':'" prop="timetype" class="w-1/2">
				<el-select v-model="data.timetype" :placeholder="$t('message.pleaseSelect')">
					<el-option :label="$t('goods.corner.timeLimit')" :value="1" />
					<el-option :label="$t('goods.corner.indefinite')" :value="2" />
				</el-select>
			</el-form-item>

			<el-form-item v-if="data.timetype == 1" :label="$t('date.activityTime') + ':'" prop="time" class="w-1/2">
				<el-date-picker v-model="data.info.time" :disabled-date="disabledDate" type="datetimerange"
					:range-separator="$t('public.to')" :start-placeholder="$t('date.startTimes')"
					:end-placeholder="$t('date.endTimes')" format="YYYY-MM-DD HH:mm:ss" value-format="x"
					:shortcuts="shortcuts" time-format="A hh:mm:ss" />
			</el-form-item>

			<el-form-item v-if="data.timetype == 2" :label="$t('date.activityTime') + ':'" prop="ditem" class="w-1/2">
				<el-date-picker v-model="data.info.ditem" :disabled-date="disabledDate" type="datetime"
					format="YYYY-MM-DD HH:mm:ss" value-format="x" style="width: 100%;"
					:placeholder="$t('message.pleaseSelect')" time-format="HH:mm:ss" />
			</el-form-item>

			<el-form-item :label="$t('marketing.guess.status') + ':'" prop="share_benefit" class="w-1/2">
				<el-select v-model="data.info.share_benefit" :placeholder="$t('message.pleaseSelect')">
					<el-option :label="$t('public.enable')" :value="1" />
					<el-option :label="$t('public.disable')" :value="2" />
				</el-select>
			</el-form-item>

			<el-form-item :label="$t('marketing.reduction.desc') + ':'" prop="desc" class="w-1/2">
				<el-input v-model="data.info.desc" type="textarea" :autosize="{ minRows: 8, maxRows: 10 }"
					:placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<el-form-item :label="$t('machine.marketing.Applicable') + ':'" prop="grouping" class="w-1/2"
				v-prmis="'machine_group_mg_getList'">

				<el-cascader :placeholder="$t('message.selectGroup')" style="width:40%;margin-right: 1%;" clearable
					:props="propss" v-model="data.groupValue" @change="getmping($event, 1)"
					@visible-change="onVisibleChange" />

				<el-select v-model="data.macping" :placeholder="$t('message.pleaseMachine')" clearable filterable
					style="width:40%;" @change="getmping($event, 2)">
					<el-option v-for="item in data.maclist" :key="item.m_id"
						:label="item.machine_id + '-' + item.machine_name" :value="item.machine_id" />
				</el-select>

				<div class="w-full dashed mt-2 p-2" v-if="data.grouping.length != 0">
					<el-tag v-for="item, key of data.grouping" :key="key" closable :disable-transitions="false"
						class="mr-2" :type="item.mg_id == undefined ? '' : 'warning'" size="large"
						@close="handleClose(key)">
						{{ item.machine_id || '' }}{{ item.mg_name || item.label || ' - ' + item.machine_name }}
					</el-tag>
				</div>

			</el-form-item>

			<el-form-item :label="$t('marketing.guess.activityContent') + ':'" prop="content" class="w-full">
				<div class="w-full border p-4">
					<div v-for="(item, key) in data.info.content">
						<div class="relative flex  flex-wrap mb-2 p-4 rounded" style="background: #FAFAFA;">

							<div class="w-4/12 mr-4 mb-4">
								<el-input v-model="item.content_name" :placeholder="$t('message.pleaseEnter')">
									<template #prepend>
										{{ $t('marketing.guess.rewardName') }}
									</template>
								</el-input>
							</div>

							<div class="w-3/12 mr-4">
								<el-select v-model="item.g_id" :placeholder="$t('message.selectProduct')" clearable
									filterable>
									<el-option v-for="item in data.godlist" :key="item.g_id"
										:label="item.g_id + ' - ' + item.g_name + ' ( ' + item.sku + ' )'"
										:value="item.g_id" />
								</el-select>
							</div>

							<div class="w-4/12 mr-4">
								<el-input v-model="item.probability" type="number"
									:placeholder="$t('message.pleaseEnter')">
									<template #prepend>
										{{ $t('marketing.guess.winningRate') }}(%)
									</template>
								</el-input>
							</div>

							<div class="w-4/12 mr-4">
								<el-input v-model="item.retain_num" type="number"
									:placeholder="$t('message.reservedEnter')">
									<template #prepend>
										{{ $t('marketing.guess.reserve') }}
									</template>
								</el-input>
							</div>

							<div class="w-1/12">
								<el-link v-if="key != 0" type="danger" :underline="false" @click="dels(key)">{{
									$t('public.del') }}</el-link>
							</div>
						</div>

					</div>

					<div class="w-full">
						<el-tag class="cursor-pointer" type="warning" size="large" effect="dark" @click="addmance">
							{{ $t('marketing.guess.addContent') }}
						</el-tag>
					</div>
				</div>
			</el-form-item>

			<el-form-item :label="$t('marketing.guess.activeConfig') + ':'" prop="config" class="w-full">
				<div class="w-full border p-4">
					<draggable :list="data.info.config" item-key="id" group="people">
						<template #item="item">
							<div class="relative flex flex-wrap mb-2 p-4 rounded" style="background: #FAFAFA;">

								<div class="w-3/12 mr-4 mb-4">
									<el-select v-model="item.element.active_type"
										:placeholder="$t('message.pleaseSelect')">
										<el-option :label="$t('marketing.guess.Single')" :value="1" />
										<el-option :label="$t('marketing.guess.continuous')" :value="2" />
									</el-select>
								</div>

								<div class="w-4/12 mr-4">
									<el-input v-model="item.element.active_num" type="number"
										:placeholder="$t('message.pleaseEnter')">
										<template #prepend>
											{{ $t('marketing.guess.drawsNum') }}
										</template>
									</el-input>
								</div>

								<div class="w-4/12 mr-4">
									<el-input v-model="item.element.gifts_num" type="number"
										:placeholder="$t('message.pleaseEnter')">
										<template #prepend>
											{{ $t('marketing.guess.giftNum') }}
										</template>
									</el-input>
								</div>

								<div class="w-3/12 mr-4">
									<el-select v-model="item.element.designated_gift"
										:placeholder="$t('message.rewardsEnter')" clearable filterable>
										<el-option v-for="(item, key) in data.info.content"
											:disabled="item.content_name == '' ? true : false"
											:label="item.content_name" :value="key" />
									</el-select>
								</div>

								<div class="w-4/12 mr-4">
									<el-input v-model="item.element.button_pic" :placeholder="$t('message.pleaseEnter')"
										readonly>
										<template #prepend>
											{{ $t('marketing.guess.buttonImage') }}
										</template>
										<template #append>
											<Upload :list="{ 'data': 'guess_img', 'list': false }" :type="1" :uptype="2"
												@exposeData="expose($event, item.index)" />
										</template>
										<template #suffix>
											<el-icon class="ml-2" size="20" @click="urlimg(item.element.button_pic)">
												<Picture />
											</el-icon>
										</template>
									</el-input>
								</div>

								<div class="w-1/12">
									<el-link v-if="item.index != 0" type="danger" :underline="false"
										@click="delfig(key)">{{
											$t('public.del') }}</el-link>
								</div>

							</div>

						</template>
					</draggable>

					<div class="w-full">
						<el-tag class="cursor-pointer" type="warning" size="large" effect="dark" @click="addgif">
							{{ $t('machine.trade.add') }}
						</el-tag>
					</div>

				</div>
			</el-form-item>

			<div class="w-1/2 text-center mt-4 ml-6">
				<div class="inline-block">
					<el-button type="primary" @click="submit(ruleFormRef)" v-prmis="'machine_group_mg_getList'">{{
						$t('public.save') }}</el-button>
					<el-button @click="cancell">{{ $t('public.cancel') }}</el-button>
				</div>
			</div>

		</el-form>

		<!-- 图片展示 -->
		<el-dialog v-model="data.demonstrate" center width="30%">
			<div class="flex justify-center">
				<el-image class="max-w-80" :src="data.pic" fit="fill" />
			</div>
		</el-dialog>

	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import Upload from '@/components/Upload/index.vue';
import draggable from "vuedraggable";
import { addlottery } from "@/api/marketing";
import { getmachineList } from '@/api/machine';
import { getgroupList, getListgroupmg } from "@/api/machine_type";
import { getgoodsList } from '@/api/goods';
import { useRouter } from "vue-router";
import { onMounted } from 'vue'
let language = ref()
const { locale } = useI18n()
onMounted(() => {
	language.value = locale.value
})
let ruleFormRef = ref<any>();
let router = useRouter()

let shortcuts = [
	{
		text: '最近七天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
			return [end, start];
		}
	},
	{
		text: '最近三十天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
			return [end, start];
		}
	},
	{
		text: '最近三个月',
		value: () => {
			const start = new Date();
			const end = new Date();
			start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
			return [end, start];
		}
	}
];

let data = reactive({
	groupValue: [],
	nodesData: [],
	mtloading: false, // 加载
	demonstrate: false, // 图片弹窗
	timetype: 1, // 1日期范围、2无限期
	original: '', // 原始数据
	pic: '', // 图片地址
	maclist: [], // 设备列表
	godlist: [], // 商品列表

	macgrouping: [], // 设备分组
	bindmacping: [], // 设备分组绑定的设备
	grouping: [], // 展示分组/设备
	macping: '', // 选中的分组/设备

	info: {
		lottery_name: '',
		time: [],
		ditem: '',
		price: '',
		desc: '',
		share_benefit: 2,
		content: [],
		config: [],
		machineList: []
	},
	rules: { // 表单验证
		lottery_name: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		price: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		ditem: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		time: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
		machineList: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' }
	},
})
const propss = reactive(
	{
		checkStrictly: true,
		lazy: true,
		multiple: false,
		async lazyLoad(node: any, resolve: any) {
			const { level, value } = node
			let nodes = await getgroupList({ pid: value });
			if (nodes.state == 100 || nodes.state == 300) {
				resolve([]);
			}
			const nodesa = nodes.data.map((item) => ({
				value: item.mg_id,
				label: item.mg_id + '-' + item.mg_name
			}))
			nodes.data.forEach(item => {
				data.nodesData.push({
					value: item.mg_id,
					label: item.mg_id + '-' + item.mg_name
				})
			})
			resolve(nodesa);
		}
	}
)
// 整理数据信息
let getinfo = () => {
	data.info = JSON.parse(data.original)

	data.info.content.push({
		id: new Date().getTime() + 1,
		content_name: '',
		retain_num: '',
		probability: '',
		g_id: ''
	})

	data.info.config.push({
		id: new Date().getTime() + 1,
		active_num: '',
		active_type: 1,
		gifts_num: '',
		designated_gift: '',
		button_pic: ''
	})

}

// 获取接口数据
let geturlinfo = async () => {
	data.original = JSON.stringify(data.info)

	// 获取设备信息
	await getmachineList().then(res => {
		if (res.state == 200) {
			data.maclist = res.data
		}
	})

	// 获取商品信息
	await getgoodsList().then(res => {
		if (res.state == 200) {
			data.godlist = res.data
		}
	})

	// 获取设备分组
	await getgroupList().then(res => {
		if (res.state == 200) {
			data.macgrouping = res.data
		}
	})

	// 获取分组中的设备
	await getListgroupmg().then(res => {
		if (res.state == 200) {
			data.bindmacping = res.data
		}
	})

	getinfo()

}

// 日期选择
let disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}

// 添加活动内容
let addmance = () => {
	data.info.content.push({
		id: new Date().getTime() + 1,
		content_name: '',
		retain_num: '',
		probability: '',
		g_id: ''
	})
}

// 删除活动内容
let dels = (e) => {
	data.info.content.splice(e, 1)
}

// 上传返回
let expose = (e, k) => {
	if (e.status == 200) {
		data.info.config[k].button_pic = e.file.response.data
	} else {
		data.info.config[k].button_pic = ''
	}
}

// 查看图片
let urlimg = (e) => {
	if (e == '') {
		return;
	}
	data.pic = e
	data.demonstrate = true;
}

// 添加活动配置
let addgif = (e) => {
	data.info.config.push({
		id: new Date().getTime() + 1,
		active_num: '',
		active_type: 1,
		gifts_num: '',
		designated_gift: '',
		button_pic: ''
	})
}

// 删除活动配置
let delfig = (e) => {
	data.info.config.splice(e, 1)
}
let onVisibleChange = () => {
	data.groupValue = []
}
// 选中分组/设备
let getmping = (e, k) => {
	let obj = ''
	let status = true
	if (k == 1) {
		// 分组
		data.nodesData.map((item) => {
			if (item.value === e[e.length - 1]) obj = item
		})
		for (let item of data.grouping) {
			if (item.value == obj.value) {
				status = false
			}
		}
	} else {
		// 设备
		data.maclist.map((item) => { if (item.machine_id === e) obj = item })
		for (let item of data.grouping) {
			if (item.m_id == obj.m_id) {
				status = false
			}
		}
		data.macping = ''
	}
	if (status) {
		data.grouping.push(obj)
	}

}

// 删除选中的设备分组/设备
let handleClose = (e) => {
	data.grouping.splice(e, 1)
}

// 保存
let submit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid, fields) => {
		if (valid) {
			let info = data.info
			let content = []
			let config = []
			let machine = []
			let obj = {
				lottery_name: info.lottery_name,
				start_time: '',
				end_time: '',
				price: info.price,
				desc: info.desc,
				share_benefit: info.share_benefit,
				content: [],
				config: [],
				machineList: [],
			}

			obj.start_time = Math.floor(data.info.ditem / 1000)
			obj.end_time = ''
			if (data.timetype == 1) {
				obj.start_time = Math.floor(data.info.time[0] / 1000)
				obj.end_time = Math.floor(data.info.time[1] / 1000)
			}

			if (data.grouping.length == 0) {
				ElMessage({
					message: $t('message.pleaseSelectMachine'),
					type: 'error'
				})
				return
			}

			if (data.grouping.length != 0) {
				let grouping = []
				for (let item of data.grouping) {
					// 设备
					if (item.mg_id != undefined) {
						data.bindmacping.map((ime) => {
							if (item.mg_id === ime.mg_id) {
								grouping.push(ime.m_id)
							}
						})
					}

					if (item.m_id != undefined) {
						grouping.push(item.m_id)
					}
					// 设备分组
					if (item.value != undefined) {
						data.bindmacping.map((ime) => {
							if (item.value === ime.mg_id) {
								if (ime.m_id !== undefined) {
									grouping.push(ime.m_id)
								}
							}
						})
					}
				}
				// 设备分组放入指定设备中
				machine = [...machine, ...grouping]
			}

			// 去除重复的设备编号
			machine = [...new Set(machine)]

			for (let item of machine) {
				obj.machineList.push({
					m_id: item
				})
			}

			for (let item of info.content) {
				if (item.content_name != '' && item.probability != '' && item.g_id != '') {
					content.push({
						content_name: item.content_name,
						retain_num: item.retain_num,
						probability: item.probability,
						g_id: item.g_id
					})
				}
			}

			if (content.length == 0) {
				ElMessage({
					message: $t('message.pleaseFillContent'),
					type: 'error'
				})
				return
			}

			obj.content = content

			for (let item of info.config) {
				if (item.active_num != '') {
					config.push({
						active_num: item.active_num,
						active_type: item.active_type,
						gifts_num: item.gifts_num || '',
						designated_gift: item.designated_gift,
						button_pic: item.button_pic || ''
					})
				}
			}

			if (config.length == 0) {
				ElMessage({
					message: $t('message.pleaseActivityConfig'),
					type: 'error'
				})
				return
			}

			obj.config = config
			data.mtloading = true
			addlottery(obj).then(res => {
				data.mtloading = false
				if (res.state == 200) {
					ElMessage({
						message: $t('message.addSuccess'),
						type: 'success'
					})
					router.back()
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			}).catch(err => {
				data.mtloading = false
				// ElMessage({
				// 	message: err.msg,
				// 	type: 'error'
				// })
			})

		}
	})
}

// 取消
let cancell = () => {
	data.grouping = []
	data.timetype = 1
	data.info.content = []
	data.info.config = []
	getinfo()
	router.back()
}

geturlinfo()

</script>

<style type="text/css">
.dashed {
	border: 2px dashed var(--el-border-color);
}
</style>
